<template>
  <div class="relative w-full h-screen overflow-hidden">
    <!-- 雪花效果背景 -->
    <div ref="canvasContainerRef" class="absolute inset-0 z-0">
      <canvas ref="canvasRef"></canvas>
    </div>

    <!-- 通话内容 -->
    <div class="relative z-10 w-full h-full flex flex-col items-center justify-center">
      <!-- 顶部返回按钮 -->
      <div class="absolute top-6 left-6 z-20">
        <button
          @click="goBack"
          class="w-12 h-12 rounded-full bg-white bg-opacity-20 flex items-center justify-center shadow-lg backdrop-blur-sm hover:bg-opacity-30 transition-all"
        >
          <span class="text-gray-800 text-xl">←</span>
        </button>
      </div>

      <!-- 对方信息 -->
      <div class="flex flex-col items-center mb-12">
        <img
          :src="roleAvatar"
          alt="avatar"
          class="w-32 h-32 rounded-full shadow-2xl border-4 border-white border-opacity-50 mb-4"
        />
        <h2 class="text-3xl font-bold text-gray-800 mt-4">{{ roleName }}</h2>
        <p class="text-gray-600 text-opacity-80 mt-2 text-lg">{{ callStatus }}</p>
        <p v-if="callDuration > 0" class="text-gray-800 font-mono mt-2 text-xl font-semibold">
          {{ formatTime(callDuration) }}
        </p>
        <p v-if="roleDescription" class="text-gray-700 text-opacity-90 mt-3 max-w-md text-center">
          {{ roleDescription }}
        </p>
      </div>

      <!-- 控制按钮 -->
      <div class="flex space-x-8">
        <!-- 静音 -->
        <button
          @click="toggleMute"
          :class="['control-btn', isMuted ? 'bg-red-400' : 'bg-gray-300 bg-opacity-30']"
        >
          <span class="text-2xl">{{ isMuted ? '🔇' : '🎤' }}</span>
          <span class="text-white text-sm mt-1">{{ isMuted ? '已静音' : '静音' }}</span>
        </button>

        <!-- 挂断 -->
        <button
          @click="endCall"
          class="w-20 h-20 rounded-full bg-red-500 text-white flex items-center justify-center text-2xl shadow-lg hover:bg-red-600 transition-all transform hover:scale-105"
        >
          📞
        </button>

        <!-- 免提 -->
        <button
          @click="toggleSpeaker"
          :class="['control-btn', isSpeakerOn ? 'bg-green-400' : 'bg-gray-300 bg-opacity-30']"
        >
          <span class="text-2xl">{{ isSpeakerOn ? '🔊' : '🔈' }}</span>
          <span class="text-white text-sm mt-1">{{ isSpeakerOn ? '免提中' : '免提' }}</span>
        </button>
      </div>

      <!-- 语音波形动画 -->
      <div class="mt-12 flex space-x-2" v-if="callStatus === '通话中'">
        <div
          v-for="n in 5"
          :key="n"
          class="w-2 bg-gray-700 rounded-full audio-bar"
          :style="{
            animationDelay: `${n * 0.1}s`,
            height: `${Math.random() * 30 + 10}px`,
          }"
        ></div>
      </div>

      <!-- 通话状态提示 -->
      <div class="absolute bottom-8 text-gray-600 text-opacity-70 text-center">
        <p v-if="callStatus === '正在呼叫...'">正在连接语音服务器...</p>
        <p v-else-if="callStatus === '通话中'">语音通话进行中</p>
        <p v-else-if="callStatus === '已挂断'">通话已结束</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, reactive, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useDevicePixelRatio } from '@vueuse/core'

const router = useRouter()
const route = useRoute()

// 雪花效果相关代码
type Snowflake = {
  x: number
  y: number
  size: number
  alpha: number
  dx: number // Horizontal drift
  dy: number // Vertical fall speed
}

// 核心优化：增大雪花尺寸、降低速度、提高透明度、增加数量，确保白色背景下可见
const snowflakeProps = {
  color: '#87CEEB', // 淡蓝色雪花
  quantity: 120, // 增加雪花数量（原80），提升密度
  speed: 0.3, // 降低下落速度（原0.8），更显轻柔且易观察
  maxRadius: 6, // 增大最大半径（原2.5），雪花更醒目
  minRadius: 2, // 增大最小半径（原0.8），避免过小看不见
}

const canvasRef = ref<HTMLCanvasElement | null>(null)
const canvasContainerRef = ref<HTMLDivElement | null>(null)
const context = ref<CanvasRenderingContext2D | null>(null)
const snowflakes = ref<Snowflake[]>([])
const canvasSize = reactive<{ w: number; h: number }>({ w: 0, h: 0 })
const { pixelRatio } = useDevicePixelRatio()

const color = computed(() => {
  const hex = snowflakeProps.color.replace(/^#/, '').padStart(6, '0')
  const bigint = parseInt(hex, 16)
  const r = (bigint >> 16) & 255
  const g = (bigint >> 8) & 255
  const b = bigint & 255
  return `${r} ${g} ${b}`
})

// 雪花效果初始化
function initSnowflakes() {
  resizeCanvas()
  createSnowflakes()
  animate()
}

function resizeCanvas() {
  if (canvasContainerRef.value && canvasRef.value && context.value) {
    snowflakes.value.length = 0
    canvasSize.w = canvasContainerRef.value.offsetWidth
    canvasSize.h = canvasContainerRef.value.offsetHeight
    canvasRef.value.width = canvasSize.w * pixelRatio.value
    canvasRef.value.height = canvasSize.h * pixelRatio.value
    canvasRef.value.style.width = `${canvasSize.w}px`
    canvasRef.value.style.height = `${canvasSize.h}px`
    context.value.scale(pixelRatio.value, pixelRatio.value)
  }
}

function createSnowflakes() {
  for (let i = 0; i < snowflakeProps.quantity; i++) {
    const snowflake = createSnowflake()
    snowflakes.value.push(snowflake)
  }
}

function createSnowflake(): Snowflake {
  const x = Math.random() * canvasSize.w
  const y = Math.random() * canvasSize.h
  // 雪花尺寸：基于配置的最大/最小半径，确保大小统一放大
  const size =
    Math.random() * (snowflakeProps.maxRadius - snowflakeProps.minRadius) + snowflakeProps.minRadius
  // 提高透明度范围（原0.3-0.6 → 0.5-0.9），雪花更清晰
  const alpha = Math.random() * 0.4 + 0.5
  // 减小水平漂移（原±0.15 → ±0.1），运动更平稳
  const dx = (Math.random() - 0.5) * 0.2
  // 下落速度：基于配置的基础速度，增加微小随机差，避免整齐划一
  const dy = Math.random() * 0.1 + snowflakeProps.speed
  return { x, y, size, alpha, dx, dy }
}

function drawSnowflake(snowflake: Snowflake) {
  if (context.value) {
    const { x, y, size, alpha } = snowflake
    context.value.beginPath()
    // 绘制圆形雪花（增大后更清晰），填充淡蓝色半透明
    context.value.arc(x, y, size, 0, Math.PI * 2)
    context.value.fillStyle = `rgba(${color.value.split(' ').join(', ')}, ${alpha})`
    context.value.fill()
  }
}

function animate() {
  if (context.value) {
    // 白色背景清除（保留轻微拖尾，增强雪花运动感）
    context.value.fillStyle = 'rgba(255, 255, 255, 0.05)'
    context.value.fillRect(0, 0, canvasSize.w, canvasSize.h)
  }

  snowflakes.value.forEach((snowflake) => {
    // 更新雪花位置（水平漂移+缓慢下落）
    snowflake.x += snowflake.dx
    snowflake.y += snowflake.dy

    // 雪花超出底部时，从顶部重新生成（循环效果）
    if (snowflake.y > canvasSize.h + snowflake.size) {
      snowflake.y = -snowflake.size
      snowflake.x = Math.random() * canvasSize.w
      // 重新生成时重置透明度和大小，保持多样性
      snowflake.alpha = Math.random() * 0.4 + 0.5
      snowflake.size =
        Math.random() * (snowflakeProps.maxRadius - snowflakeProps.minRadius) +
        snowflakeProps.minRadius
    }

    // 雪花超出左右边界时，从另一侧重新生成
    if (snowflake.x > canvasSize.w + snowflake.size) {
      snowflake.x = -snowflake.size
    } else if (snowflake.x < -snowflake.size) {
      snowflake.x = canvasSize.w + snowflake.size
    }

    drawSnowflake(snowflake)
  })

  requestAnimationFrame(animate)
}

// 通话功能相关代码
// 从路由参数获取角色信息
// const roleId = ref((route.query.roleId as string) || '')
const roleName = ref((route.query.roleName as string) || '小助手')
const roleAvatar = ref((route.query.roleAvatar as string) || 'https://via.placeholder.com/120')
const roleDescription = ref((route.query.roleDescription as string) || '')

const callStatus = ref('正在呼叫...')
const callDuration = ref(0)
const isMuted = ref(false)
const isSpeakerOn = ref(false)
let timer: number | null = null

// 模拟通话建立
onMounted(() => {
  // 初始化雪花效果
  if (canvasRef.value) {
    context.value = canvasRef.value.getContext('2d')
  }
  initSnowflakes()
  window.addEventListener('resize', initSnowflakes)

  // 通话逻辑
  setTimeout(() => {
    callStatus.value = '通话中'
    startTimer()
  }, 2000)
})

onBeforeUnmount(() => {
  if (timer) clearInterval(timer)
  window.removeEventListener('resize', initSnowflakes)
})

// 返回主页
const goBack = () => {
  if (callStatus.value === '通话中') {
    if (confirm('确定要结束通话并返回吗？')) {
      endCall()
    }
  } else {
    router.push('/')
  }
}

// 计时器
const startTimer = () => {
  timer = setInterval(() => {
    callDuration.value++
  }, 1000)
}

// 时间格式化
const formatTime = (seconds: number) => {
  const m = String(Math.floor(seconds / 60)).padStart(2, '0')
  const s = String(seconds % 60).padStart(2, '0')
  return `${m}:${s}`
}

// 按钮功能
const toggleMute = () => {
  isMuted.value = !isMuted.value
}

const toggleSpeaker = () => {
  isSpeakerOn.value = !isSpeakerOn.value
}

const endCall = () => {
  callStatus.value = '已挂断'
  if (timer) clearInterval(timer)

  // 2秒后自动返回主页
  setTimeout(() => {
    router.push('/')
  }, 2000)
}
</script>

<style scoped>
/* 确保根容器背景为纯白色，雪花对比更明显 */
.relative {
  background-color: #ffffff;
}

.control-btn {
  @apply w-16 h-16 rounded-full flex flex-col items-center justify-center shadow-lg backdrop-blur-sm transition-all duration-300;
}

.control-btn:hover {
  transform: scale(1.05);
}

.audio-bar {
  animation: pulse 1.5s infinite ease-in-out;
}

@keyframes pulse {
  0%,
  100% {
    transform: scaleY(0.5);
    opacity: 0.7;
  }
  50% {
    transform: scaleY(1);
    opacity: 1;
  }
}
</style>
